package com.bpzj.util.config;

import java.nio.charset.StandardCharsets;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;

/**
 * @author bpzj 2019/8/27 15:59 学习
 * {@link  org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration}
 */
@Configuration
@ConditionalOnClass({RestTemplateBuilder.class, RestTemplate.class, RestOperations.class})
@AutoConfigureAfter({RestTemplateAutoConfiguration.class})
public class RestTemplateConfig {

  @Autowired
  RestTemplateBuilder builder;

  @Bean
  @ConditionalOnMissingBean({RestOperations.class, RestTemplate.class})
  public RestTemplate restTemplate() {
    RestTemplate restTemplate = builder.build();

    // 使用 utf-8 编码集的 converter 替换默认的 converter
    // (默认的 string converter 的编码集为 "ISO-8859-1")
    List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
    messageConverters.removeIf(converter -> converter instanceof StringHttpMessageConverter);
    messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
    return restTemplate;
  }
}
